package top.rainbowecho.gateway.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import top.rainbowecho.gateway.security.property.SecurityProperties;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author rainbow
 * @since 2020/4/24 21:00
 */
@Configuration
public class ZuulCorsConfiguration {
    private SecurityProperties securityProperties;

    @Autowired
    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        SecurityProperties.SecurityCorsProperties corsProperties = this.securityProperties.getCors();
        //配置初始化对象
        CorsConfiguration configuration = new CorsConfiguration();
        //允许跨域的域名，如果要携带cookie，不能写* 。  *：代表所有的域名都可以访问
        List<String> filterOrigin = corsProperties.getAllowOrigin().stream()
                .filter(e -> !StringUtils.equals(e, "*")).collect(Collectors.toList());
        configuration.setAllowedOrigins(filterOrigin);
        configuration.setAllowCredentials(corsProperties.isAllowCredentials());
        configuration.setAllowedMethods(corsProperties.getAllowMethod());
        configuration.setAllowedHeaders(corsProperties.getAllowHeader());

        //初始化cors配置源对象
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration(corsProperties.getPathMapping(), configuration);
        return configurationSource;
    }

}
